import { UserManager, User } from 'oidc-client-ts'

const hostUrl = window.location.origin

const manager = new UserManager({
  authority: `${import.meta.env.VITE_AUTHORITY}`,
  client_id: `${import.meta.env.VITE_CLIENT_ID}`,
  redirect_uri: hostUrl + '/ad/callback',
  scope: `${import.meta.env.VITE_SCOPE}`
})

manager.events.addAccessTokenExpired(() => {
  alert('Сессия истекла, нужно авторизоваться заново!')
  manager
    .signoutRedirect()
    .then(() => (window.location.href = hostUrl))
    .catch((err) => console.log(err))
})

manager.events.addUserSignedOut(() => {
  manager.signoutRedirect().catch((err) => console.log(err))
})

export default class UserManagerAD {
  // Redirect of the current window to the authorization endpoint.
  signIn(): void {
    window.localStorage.setItem('contactsADRedirectUrl', window.location.href)
    manager.signinRedirect().catch(function (err) {
      console.error(err)
    })
  }

  signInRedirectCallback(): Promise<User> {
    return manager.signinRedirectCallback()
  }

  // Redirect of the current window to the end session endpoint
  signOut(): void {
    manager
      .signoutRedirect()
      .then(function () {
        window.location.href = hostUrl
      })
      .catch(function (err) {
        console.error(err)
      })
  }

  // Get logged in User or redirect to signIn page
  getUser(): Promise<User | null> {
    return new Promise((resolve, reject) => {
      manager
        .getUser()
        .then((user) => {
          if (user == null) {
            this.signIn()
            return resolve(null)
          } else {
            return resolve(user)
          }
        })
        .catch(function (err) {
          console.error(err)
          return reject(err)
        })
    })
  }
}
